import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:wowhy/models/admin_user_info.dart';
import 'package:wowhy/models/error_info.dart';
import 'package:wowhy/service_locator.dart';
import 'package:wowhy/services/admin_user_service.dart';
import 'package:wowhy/services/navigate_service.dart';
import 'package:wowhy/utils/message.dart';
import 'action.dart';
import 'state.dart';

Effect<AdminUserEditState> buildEffect() {
  return combineEffects(<Object, Effect<AdminUserEditState>>{
    Lifecycle.initState: _init,
    AdminUserEditAction.onSave: _onSave,
    AdminUserEditAction.onReset: _onReset,
  });
}

void _init(Action action, Context<AdminUserEditState> ctx) async {
  if (ctx.state.mode != 'add') {
    AdminUserInfo result =
        await AdminUserService.instance.getById(ctx.state.id);
    if (result == null) {
      getIt<NavigateService>().pop();
    }

    ctx.dispatch(AdminUserEditActionCreator.load(result));
  }
}

void _onSave(Action action, Context<AdminUserEditState> ctx) async {
  if (!ctx.state.formKey.currentState.validate()) {
    return;
  }

  try {
    AdminUserInfo result = await MessageUtil.blocking(ctx.context, () {
      if (ctx.state.mode == 'add') {
        return AdminUserService.instance.create(ctx.state.formModel);
      } else {
        return AdminUserService.instance.update(ctx.state.id, {
          'nickName': ctx.state.formModel.nickName,
        });
      }
    });

    MessageUtil.notification(ctx.context, "保存成功");
    getIt<NavigateService>().pop(result);
  } on ErrorInfo {
    // nothing
  }
}

void _onReset(Action action, Context<AdminUserEditState> ctx) async {
  if ((await MessageUtil.confirm(ctx.context, '是否重置表单？')) ==
      AlertActionResult.yes) {
    ctx.state.formKey.currentState.reset();
  }
}
